import axios from 'axios'
import { Modal } from 'ant-design-vue'

const instance = axios.create({
  baseURL: '', // /url
  withCredentials: true,
  timeout: 120 * 1000
})

// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//
// instance.defaults.headers = {'Access-Control-Allow-Origin': '*'};

instance.interceptors.request.use(
  config => {
    const loginToken = sessionStorage.getItem('LOGIN_TOKEN');
    if (loginToken) {
      config.headers.LOGIN_TOKEN = loginToken
    }
    return config;
  },
  error => Promise.error(error))

function checkLogin(response) {
  const result = response.data
  if (result.errorCode === 301) { // 登录已过期
    Modal.error({
      title: result.message,
      onOk() {
        window.location.href = "/login"
      }
    })
  } else if (result.errorCode === 302) { // 没有权限
    Modal.error({
      title: result.message
    })
    return Promise.reject(response);
  }
  return Promise.resolve(response);
}

instance.interceptors.response.use(
  res => {
    return res.status === 200 ? checkLogin(res) : Promise.reject(res)
  },
  error => {
    const {response} = error;
    if (response) {
      return Promise.reject(response);
    } else {
      return Promise.reject(error);
    }
  })

export default instance
